package com.yk._08BlockingQueue;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;

public class _08BlockingQueue {

    public static void main(String[] args) {
        throwExceptionFunc();

    }
    public static void throwExceptionFunc(){
        ArrayBlockingQueue arrayBlockingQueue = new ArrayBlockingQueue<>(2);

        for (int i = 0; i < 3; i++) {
            arrayBlockingQueue.add(i); //队列装满时 再添加元素 会抛出异常
        }
        for (int i = 0; i < 3; i++) {
            arrayBlockingQueue.remove();//// 当队列没有元素时 再移除元素 会抛出异常

        }
    }

    public static void unThrowExceptionFunc(){
        ArrayBlockingQueue<String> blockingQueue = new ArrayBlockingQueue<>(2);

        for (int i = 0; i < 3; i++) {
            System.out.println(blockingQueue.offer("a")); //不会抛出异常 添加成功了会返回true 失败返回false
        }

        for (int i = 0; i < 3; i++) {
            System.out.println(blockingQueue.poll()); // 成功取值返回该值 取值失败返回null
        }
    }

    public static void unThrowExceptionFunc2() throws InterruptedException {
        ArrayBlockingQueue<String> blockingQueue = new ArrayBlockingQueue<>(2);

        for (int i = 0; i < 3; i++) {
            System.out.println("adding");
            blockingQueue.put("a"); //队列装满时 会阻塞
            System.out.println("add success");
        }

        for (int i = 0; i < 3; i++) {
            System.out.println(blockingQueue.take());
        }
    }

    public static void unThrowExceptionFunc3() throws InterruptedException {
        ArrayBlockingQueue<String> blockingQueue = new ArrayBlockingQueue<>(2);

        for (int i = 0; i < 3; i++) {
            System.out.println("adding....");
            blockingQueue.offer("a",10, TimeUnit.SECONDS); //队列装满时 会阻塞 但是阻塞有时限 超时就会放弃添加
            System.out.println("add success");
        }

        for (int i = 0; i < 3; i++) {
            System.out.println(blockingQueue.poll(10, TimeUnit.SECONDS));
        }
    }
}
